package com.sdy.dcsb.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.EsbConsumerTree;
import com.sdy.dcsb.biz.model.EsbConsumerTreeCount;
import com.sdy.dcsb.biz.service.EsbConsumerTreeService;
import com.sdy.dcsb.biz.service.UserOperationLogService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 服务消费者树表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-09-27
 */
@Slf4j
@Controller
@RequestMapping("/EsbConsumerTree")
@Api(tags = "消费者目录树相关接口")
public class EsbConsumerTreeController extends BaseController {
    @Autowired
    private EsbConsumerTreeService esbConsumerTreeService;
    @Autowired
    private UserOperationLogService userOperationLogService;

    /**
     * 查询子目录
     * @param id 主键,当前节点id
     * @param haschildren ,有无子节点 1:有,0:无
     * @param unrequiredId ,不需要展示的节点id
     * @return
     */
    @GetMapping("/listSubId")
    @ResponseBody
    @ApiOperation("查询子目录，最高父节点为0")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "Integer", name = "unrequiredId", value = "不需要展示的节点id"),
    })
    public Response listSubId(Integer id, Integer haschildren, Integer unrequiredId) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        QueryWrapper<EsbConsumerTree> wrapper = new QueryWrapper<>();
        if(!isEmpty(haschildren)) {
            wrapper.eq("haschildren",haschildren);
        }
        if(!isEmpty(unrequiredId)) {
            wrapper.ne("id",unrequiredId);
        }
        wrapper.eq("par_id",id);
        wrapper.orderByDesc("code");
        wrapper.orderByAsc("id");
        List<EsbConsumerTree> result = esbConsumerTreeService.list(wrapper);
        List<EsbConsumerTreeCount> resultCount = new ArrayList();
        for(int i=0; i< result.size(); i++) {
            EsbConsumerTreeCount esbConsumerTreeCount = new EsbConsumerTreeCount();
            esbConsumerTreeCount.setId(result.get(i).getId());
            esbConsumerTreeCount.setCode(result.get(i).getCode());
            esbConsumerTreeCount.setHaschildren(result.get(i).getHaschildren());
            esbConsumerTreeCount.setLvl(result.get(i).getLvl());
            esbConsumerTreeCount.setName(result.get(i).getName());
            esbConsumerTreeCount.setStatus(result.get(i).getStatus());
            esbConsumerTreeCount.setParId(result.get(i).getParId());
            esbConsumerTreeCount.setCount(systemCount(result.get(i).getId(), 0));
            resultCount.add(i, esbConsumerTreeCount);
        }
        return Response.success(resultCount);
    }

    /**
     * 查询数据
     * @param id ,当前节点id
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询当前节点目录数据,haschildren=1时调用此接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
    })
    public Response select(Integer id) {
        if(!isEmpty(id)) {
            return Response.success(esbConsumerTreeService.getById(id));
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 删除数据
     * @param id ,当前节点id
     * @param haschildren ,当前节点有无子节点 1:有,0:无
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation("删除当前节点目录数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
    })
    public Response delete(HttpServletRequest request, Integer id, Integer haschildren) {
        if (haschildren == 1) {
            if(isEmpty(id)) {
                return Response.error("请求id不能为空");
            }
            QueryWrapper<EsbConsumerTree> wrapper = new QueryWrapper<>();
            wrapper.eq("par_id",id);
            List<EsbConsumerTree> result = esbConsumerTreeService.list(wrapper);
            if(result.size() >= 1 || id == 1) {
                return Response.error("当前目录下有数据不能被删除！");
            }else {
                userOperationLogService.savaUserLog(request, "删除消费者树目录：" +
                        esbConsumerTreeService.getById(id).getName());
                if(esbConsumerTreeService.removeById(id)) {
                    return Response.success("删除目录成功");
                }else {
                    return Response.error("删除目录失败！");
                }
            }
        }else {
            return Response.error("当前目录不能被删除");
        }
    }

    /**
     * 修改目录名称
     * @param id ,当前节点id
     * @param name ,目录名称
     * @param haschildren ,当前节点有无子节点 1:有,0:无
     * @return
     */
    @GetMapping("/updateName")
    @ResponseBody
    @ApiOperation("修改当前节点目录名称")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "目录名称"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
    })
    public Response updateName(HttpServletRequest request, Integer id, String name, Integer haschildren) {
        if (haschildren == 1) {
            EsbConsumerTree esbConsumerTree = new EsbConsumerTree();
            if(!isEmpty(name) || isEmpty(id)) {
                try {
                    name = URLDecoder.decode(name,"utf-8");
                }catch(IOException e) {

                }
                esbConsumerTree.setName(name);
                userOperationLogService.savaUserLog(request, "修改消费者树目录：" +
                        esbConsumerTreeService.getById(id).getName() + "--->" + name);
                return Response.success(esbConsumerTreeService.update(esbConsumerTree, new UpdateWrapper<EsbConsumerTree>().eq("id", id)));
            }else {
                return Response.error("请求id或者目录名称不能为空");
            }
        }else {
            return Response.error("当前目录名称不能被修改");
        }
    }

    /**
     * 新增子目录
     * @param id ,当前节点id
     * @param lvl ,当前节点层级
     * @param haschildren ,当前节点有无子节点 1:有,0:无
     * @param name ,目录名称
     * @return
     */
    @GetMapping("/insertSubId")
    @ResponseBody
    @ApiOperation("新增当前目录的子目录")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "lvl", value = "当前节点层级"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "目录名称"),
    })
    public Response insertSubId(HttpServletRequest request, Integer id, Integer lvl, Integer haschildren, String name) {
        if(isEmpty(id) || isEmpty(lvl)) {
            return Response.error("当前节点id或者当前节点层级不能为空");
        }
        if (haschildren == 1) {
            EsbConsumerTree esbConsumerTree = new EsbConsumerTree();
            if(!isEmpty(name)) {
                try {
                    name = URLDecoder.decode(name,"utf-8");
                }catch(IOException e) {

                }
                esbConsumerTree.setCode(0);
                esbConsumerTree.setHaschildren(1);
                esbConsumerTree.setLvl(lvl+1);
                esbConsumerTree.setName(name);
                esbConsumerTree.setStatus("1");
                esbConsumerTree.setParId(id);
                userOperationLogService.savaUserLog(request, "新增消费者树目录：" + name);
                return Response.success(esbConsumerTreeService.save(esbConsumerTree));
            }else {
                return Response.error("目录名称不能为空");
            }
        }else {
            return Response.error("当前目录已是最底层，无法新增目录");
        }
    }

    /**
     * 节点迁移
     * @param id ,当前节点id
     * @param targetId ,目标节点id
     * @param targetLvl ,目标节点层级
     * @return
     */
    @GetMapping("/migrate")
    @ResponseBody
    @ApiOperation("节点迁移")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "targetId", value = "目标节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "targetLvl", value = "目标节点层级"),
    })
    public Response migrate(HttpServletRequest request, Integer id, Integer targetId, Integer targetLvl) {
        if(isEmpty(id) || isEmpty(targetId) || isEmpty(targetLvl)) {
            return Response.error("当前节点id或目标节点id或目标节点层级不能为空");
        }
        if(id.equals(targetId)) {
            return Response.error("不能迁移到自己目录下，请重新选择!");
        }
        EsbConsumerTree esbConsumerTree = new EsbConsumerTree();
        esbConsumerTree.setLvl(targetLvl+1);
        esbConsumerTree.setParId(targetId);
        userOperationLogService.savaUserLog(request, "迁移消费者树目录：" + esbConsumerTreeService.getById(id).getName() +
                "--->" + esbConsumerTreeService.getById(targetId).getName());
        esbConsumerTreeService.update(esbConsumerTree, new UpdateWrapper<EsbConsumerTree>().eq("id", id));
        return Response.success("迁移成功");
    }

    /**
     * 消费者系统目录,查询日志选择消费者时使用
     * @return
     */
    @GetMapping("/selectSystem")
    @ResponseBody
    @ApiOperation("所有消费者系统目录,查询服务日志时选择系统名称使用")
    @ApiImplicitParams({
    })
    public Response selectSystem() {
        QueryWrapper<EsbConsumerTree> wrapper = new QueryWrapper<>();
        wrapper.eq("haschildren",0);
        List<EsbConsumerTree> result = esbConsumerTreeService.list(wrapper);
        return Response.success(result);
    }

    /**
     * 查询当前目录下消费者系统数量
     * @param id 当前节点id
     * @param count 初始值0
     * @return
     */
    private Integer systemCount(Integer id, Integer count) {
        QueryWrapper<EsbConsumerTree> wrapperSystem = new QueryWrapper<>();
        wrapperSystem.eq("par_id",id);
        wrapperSystem.ne("code",0);
        List<EsbConsumerTree> resultSystem = esbConsumerTreeService.list(wrapperSystem);
        count = count + resultSystem.size();
        QueryWrapper<EsbConsumerTree> wrapper = new QueryWrapper<>();
        wrapper.eq("par_id",id);
        wrapper.eq("code",0);
        List<EsbConsumerTree> result = esbConsumerTreeService.list(wrapper);
        for(int i=0; i<result.size(); i++) {
            count = systemCount(result.get(i).getId(), count);
        }
        return count;
    }

}
